package com.project.mariadb;

import com.google.zxing.WriterException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/user")
public class Controller {

    private static final Logger log = LoggerFactory.getLogger(Controller.class);


    @Resource
    private UserRepository userRepository;

    @Resource
    private UserDao userDao;


    @RequestMapping("/save/{num}")
    public Object save(@PathVariable("num") Integer num) {

        StopWatch stopWatch = new StopWatch();

        List<User> users = new ArrayList<>(num);

        for (Integer i = 0; i < num; i++) {

            User user = new User();
            user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            user.setName(" name ".concat(i.toString()));

            users.add(user);
        }


        log.info(" 开始存储 ");
        stopWatch.start();
        Map<String, List<User>> map = new HashMap<>(1);
        map.put("list", users);
        long count = userDao.saveList(map);
        stopWatch.stop();
        log.info(" 共耗时  {} /  s , 共存储 {} 条数据", stopWatch.getTotalTimeSeconds(), count);

        return count;

    }

    @RequestMapping("/find")
    public Object find() {
        return this.userRepository.findAll();
    }


    @RequestMapping("/qrcode")
    public void qrcode(HttpServletResponse response) throws IOException, WriterException {
        QRCodeUtil.writeToStream("content", response.getOutputStream(), 100, 100);
    }


}
